package com.tbit.uqbike.webmanager.controller.interceptor;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * created by Kang on 2019/3/28 13:55
 * description:拦截器配置
 */
public class LanguageInterceptor extends HandlerInterceptorAdapter {
    public static final Integer DEF_ZONE = 8 * 60;
    public static final Integer MAX_ZONE = 12 * 60;
    public static final Integer MIN_ZONE = -12 * 60;

    public static final Locale EN_LOCAL = new Locale("en", "US");
    public static final Locale CN_LOCAL = new Locale("zh", "CN");
    public static final Locale TW_LOCAL = new Locale("zh", "TW");

    public static Integer parseZone(String zone) {
        // 默认为东8区
        Integer izone = DEF_ZONE;
        if (!StringUtils.isEmpty(zone)) {
            try {
                Integer i = Integer.parseInt(zone);
                if (i >= MIN_ZONE && i <= MAX_ZONE) {
                    izone = i;
                }
            } catch (Exception e) {

            }
        }
        return izone;
    }

    public static Locale parseLocaleValue(String lang) {
        // 默认语言是英文
        if (!StringUtils.isEmpty(lang)) {
            if ("en".equals(lang)) {
                return EN_LOCAL;
            } else if ("cn".equals(lang)) {
                return CN_LOCAL;
            } else if ("tw".equals(lang)) {
                return TW_LOCAL;
            }
        }
        return CN_LOCAL;
    }

    /**
     * 说明：1、springMVC四种方式
     * 1.1、cookie 方式（不考虑）
     * 1.2、session 集群方式失效
     * 1.3、acceptHeader 请求头方式
     * 1.4、fixed  固定方式(采用这种方式，只拦截登录接口，设置语言)
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String lang = request.getHeader(HttpHeadName.REQUEST_ATTR_NAME_LANG);

        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
        }
        Locale locale = parseLocaleValue(lang);
        localeResolver.setLocale(request, response, locale);
        request.setAttribute(HttpHeadName.REQUEST_ATTR_NAME_LANG, locale);

        String zone = request.getHeader(HttpHeadName.REQUEST_ATTR_NAME_ZONE);
        Integer izone = parseZone(zone);
        request.setAttribute(HttpHeadName.REQUEST_ATTR_NAME_ZONE, izone);
        return true;

    }
}
